package cn.liyao.web.interceptor;

import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.liyao.tool.annotation.RequireToken;
import cn.liyao.tool.api.R;
import cn.liyao.tool.api.ResultCode;
import cn.liyao.web.holder.CurrentUserIdHolder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


@Configuration
public class TokenInterceptor implements HandlerInterceptor {


    @Value("${jwt.token}")
    private String jwtToken;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {




        try{
            Method method = ((HandlerMethod) handler).getMethod();
            RequireToken annotation = method.getAnnotation(RequireToken.class);
            String token = request.getHeader("Authorization");
            if (annotation != null && annotation.required()) {
                if (token == null || !JWTUtil.verify(token, jwtToken.getBytes())) {
                    String jsonContent = JSONUtil.toJsonStr(R.fail(ResultCode.CLIENT_UN_AUTHORIZED));
                    response.setContentType("application/json;charset=UTF-8");
                    ServletOutputStream out = response.getOutputStream();
                    out.write(jsonContent.getBytes("UTF-8"));
                    out.flush();
                    out.close();
                    return false;
                } else {
                    JWT jwt = JWTUtil.parseToken(token);
                    String userId = jwt.getPayloads().getStr("userId");
                    CurrentUserIdHolder.setCurrentUser(userId);
                }
            }
        }catch (Exception e){
            return false;
        }
        return true;
    }
}